package org.example;

import org.example.自定义双端队列.LinkedListDeque;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 二叉树Z字层序遍历
 */
public class E01Leetcode103 {

    public static void main(String[] args) {
        TreeNode root = new TreeNode(
                new TreeNode(
                        new TreeNode(4),
                        2,
                        new TreeNode(5)),
                1,
                new TreeNode(
                        new TreeNode(6),
                        3,
                        new TreeNode(7)));
        LinkedBlockingQueue<TreeNode> queue = new LinkedBlockingQueue<>();
        queue.offer(root);
        int c1 = 1;
        while (!queue.isEmpty()) {
            int c2 = 0;
            for (int i = 0; i < c1; i++) {
                TreeNode node = queue.poll();
                System.out.print(node + " ");
                if (node.left != null) {
                    queue.offer(node.left);
                    c2++;
                }
                if (node.right != null) {
                    queue.offer(node.right);
                    c2++;
                }
            }
            System.out.println();
            c1 = c2;
        }
    }


    /**
     * 把数据放入集合中
     * @param root
     * @return
     */
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) return res;
        LinkedBlockingQueue<TreeNode> queue = new LinkedBlockingQueue<>();
        queue.offer(root);
        int c1 = 1;
        boolean odd = true;
        while (!queue.isEmpty()) {
            int c2 = 0;
            List<Integer> list = new ArrayList<>();
            LinkedList<Integer> level = new LinkedList<>();
            for (int i = 0; i < c1; i++) {
                TreeNode node = queue.poll();
                list.add(node.val);
//                System.out.print(node + " ");
                // 实现关键点
                if (odd) {
                    level.addLast(node.val);
                } else {
                    level.addFirst(node.val);
                }
                if (node.left != null) {
                    queue.offer(node.left);
                    c2++;
                }
                if (node.right != null) {
                    queue.offer(node.right);
                    c2++;
                }
            }
            res.add(list);
//            System.out.println();
            c1 = c2;

        }
        return res;
    }
}
